
define(['ionic', 'services'], function () {
    angular.module('U9Mobile.services')
        .factory('Push',['$q','UserService','UtilService','AppManager','$timeout','$ionicHistory','$state',function ($q,UserService,UtilService,AppManager,$timeout,$ionicHistory,$state) {
            var self=this;
            self.isStoped=false;
            var configList={},localMessage={MessageRemind:false,ClientMessage:false},initOpt=false;
            configList.msg={};
            var tmpIndex={
                "200010":0,
                "100003":1,
                "100018":10,
                "100005":7,
                "100002":2,
                "100001":3,
                "100016":4,
                "100013":5,
                "100012":6,
                "100014":9,
                "100007":8
            }, temp=[
                {name:'客户消息提醒',IsOpen:true,MessageTypeValue:200010},
                {name:'审批消息提醒',IsOpen:true,MessageTypeValue:100003},
                {name:'个人消息提醒',IsOpen:true,MessageTypeValue:100002},
                {name:'系统消息提醒',IsOpen:true,MessageTypeValue:100001},
                {name:'留言消息提醒',IsOpen:true,MessageTypeValue:100016},
                {name:'公告消息提醒',IsOpen:true,MessageTypeValue:100013},
                {name:'会议消息提醒',IsOpen:true,MessageTypeValue:100012},
                {name:'个人任务提醒',IsOpen:true,MessageTypeValue:100005},
                {name:'个人日历提醒',IsOpen:true,MessageTypeValue:100007},
                {name:'协同事项提醒',IsOpen:true,MessageTypeValue:100014},
                {name:'公文消息提醒',IsOpen:true,MessageTypeValue:100018}
            ];
            configList.mute={name:'静音',IsOpen:false};
            configList.GlobalSwitch={name:'消息通知',IsOpen:true};
            function resetOpt(){
                var arry={};
                for(var k in tmpIndex){
                    arry[k]=temp[tmpIndex[k]];
                }
                return arry;
            }
            configList.msg=resetOpt();
            return {

                callback:function(notice){
                    $ionicHistory.nextViewOptions({
                        historyRoot: true,
                        expire: 300
                    });
                    var params="#/messages/",typeID="MessageRemind",appID="MessageRemind";

                    if(notice.MessageType&&notice.MessageType=="客户动态"){
                        params="#/";
                        typeID="ClientMessage";
                        appID="ClientMessage";
                    }
                    if(!AppManager.checkAppInstalled(appID)){
                        var notice="您还没有下载"+(appID=="MessageRemind"?"消息通知":"客户动态")+",先去下载吧";
                        UtilService.confirm(notice,"消息提醒").then(function(res){
                            if(res){
                                $state.go('app.download');
                            }else{
                                return false;
                            }
                        })
                        return ;
                    }
                    try{
                        AppManager.setActiveAppId(appID);
                        var msgType,msgId;
                        msgId=notice['MessageID'];
                        switch (notice.MessageType){
                            case "系统消息":msgType="SystemMessage";break;
                            case "个人消息":msgType="CSMessage";break;
                            case "工作流消息":msgType="WorkFlowMessage";break;
                            case "单据留言":msgType="DocMsg";break;
                            case "公告消息":msgType="boardMsg";break;
                            case "会议消息":msgType="ConferenceMsg";break;
                            case "个人任务":msgType="CSTaskRemind";break;
                            case "个人日历":msgType="CSCalendarRemind";break;
                            case "协同事项":msgType="CoopTaskMsg";break;
                            case "公文消息":msgType="FDocMessageNav";break;
                            case "客户动态":msgType="pushmessages";break;
                        }
                        if(localMessage[typeID]){
                            /*if (window.Analytics) {
                                window.Analytics.analytics("clickApp","消息通知");
                            }*/
                            AppManager.setActiveAppId(typeID);
                            $state.go('app.temp',{'param':params+msgType+"/"+msgId})

                        }else{
                            AppManager.checkLicense("MessageRemind").then(function (data) {
                                localMessage[typeID]=true;
                                if (data.flag === '000000') {
                                    AppManager.setActiveAppId(typeID);
                                    /*if (window.Analytics) {
                                        window.Analytics.analytics("clickApp","消息通知");
                                    }*/
                                    $state.go('app.temp',{'param':params+msgType+"/"+msgId})
                                } else {
                                    UtilService.alert(data.desc);
                                }
                            }, function (error) {
                                UtilService.alert('checkLicense error:' + error);
                            });
                        }
                    }catch(err){
                        alert("error"+err.message)
                    }


                },
                stop: function () {
                    if (push) return;
                    window.plugins.jPushPlugin.stopPush();

                },
                setBadge: function (badge) {
                    if (!self.isStoped) {
                        window.plugins.jPushPlugin.setBadge(badge);
                    }
                },
                resume: function () {
                    window.plugins.jPushPlugin.resumePush();
                },
                getRegistryID: function (callback) {
                    window.plugins.jPushPlugin.getRegistrationID(callback);
                },
                setAlis: function (obj) {
                    initOpt=false;
                    //if (self.isStoped) return;
                    if (!window.plugins || !window.plugins.jPushPlugin) {
                        return;
                    }
                    var alias=obj['enterprise_id']+'_'+(obj['user_code']?obj['user_code'].toLowerCase():" ");
                    if(alias){
                        window.plugins.jPushPlugin.setAlias(alias);
                    }

                },
                set settingList(config){
                    angular.copy(config,configList);
                },
                get settingList(){
                    return {msg:configList.msg,mute:configList.mute||""};
                },
                SyncService:function(Enumerate){
                    var d=$q.defer();
                    var params=[UserService.getPushConfig().enterprise_id,UserService.getPushConfig().user_code,Enumerate.MessageTypeValue,Enumerate.IsOpen];
                    u9.callSV({
                        name: 'UFIDA.U9.ISV.MFGRestMessageSV.Message.IOperateMessAsso',
                        params: params,
                        onSuccess: function (data) {
                            configList.msg[Enumerate.MessageTypeValue].IsOpen=Enumerate.IsOpen;
                            if(data){
                                d.resolve(Enumerate.IsOpen)
                            }else{
                                d.reject(!Enumerate.IsOpen);
                            }
                        },
                        onFailure: function (err) {
                            console.log('同步设置失败');
                            d.reject(!Enumerate.IsOpen);
                        }
                    });
                    return d.promise;
                },
                setMute:function(mute,global){
                    var d=$q.defer();
                    u9.callSV({
                        name: 'UFIDA.U9.ISV.MFGRestMessageSV.Message.IOperateVoice',
                        params: [UserService.getPushConfig().user_code,mute,global],
                        onSuccess: function (data) {
                            configList.mute.IsOpen=mute;
                            configList.GlobalSwitch.IsOpen=global;
                            console.log('同步设置成功');
                            d.resolve(mute.IsOpen);
                        },
                        onFailure: function (err) {
                            console.log('同步设置失败');
                            d.reject(!mute.IsOpen);
                        }
                    });
                    return d.promise;
                },
                 set jpushStatus(status){
                  self.isStoped=status;
                },
                get jpushStatus(){
                    return self.isStoped;
                },
                initOptSetting:function(){
                    var d=$q.defer();
                    if(initOpt){
                        d.resolve(configList);
                    }else{
                        var params=[UserService.getPushConfig().enterprise_id,UserService.getPushConfig().user_code];
                        if(!params[0]){
                            d.resolve(false);
                        }else{
                            u9.callSV({
                                name: 'UFIDA.U9.ISV.MFGRestMessageSV.Message.IGetMessageAssoInfo',
                                params: params,
                                onSuccess: function (data) {
                                    initOpt=true;
                                    if(data.length==0||!data[0].MessageTypeName){
                                        d.resolve(configList);
                                    }else{
                                        configList.mute.IsOpen=data[0].IsMute;
                                        configList.GlobalSwitch.IsOpen=data[0].GlobalSwitch;
                                        data.forEach(function(v,i,self){
                                            try{
                                                configList.msg[v.MessageTypeValue]=angular.extend(temp[tmpIndex[v.MessageTypeValue]],v)
                                            }catch(err){
                                                console.log(err)
                                            }

                                        })
                                        d.resolve(configList);
                                    }


                                },
                                onFailure: function (err) {
                                    console.log(err);
                                    d.resolve(configList)
                                }
                            });
                        }

                    }

                    return d.promise;
                }
            };
        }]);
});